<template>
  <div class="notice-table">
    <!-- 顶部搜索栏 -->
    <el-row class="search-bar" style="margin-bottom: 20px; background-color: #fff; padding: 15px;">
      <el-col :span="24">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="标题">
            <el-input style="width: 170px;" v-model="searchForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <!-- <el-form-item label="发布状态">
            <el-select v-model="searchForm.state" placeholder="请选择状态" style="width: 170px;">
              <el-option label="草稿" :value="0"></el-option>
              <el-option label="已发布" :value="1"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="起始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 170px;"
              :picker-options="{
                disabledDate: time => {
                  return time.getTime() > new Date().setHours(23, 59, 59, 999);
                }
              }"  
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="datetime"
              placeholder="选择日期时间" 
              style="width: 170px;"
              :picker-options="{
                disabledDate: time => {
                  return time.getTime() > new Date().setHours(23, 59, 59, 999);
                }
              }"
              default-time="23:59:59" 
            >
            </el-date-picker>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="searchNotices">查询</el-button>
          </el-form-item>
          <el-form-item>
            <!-- 添加公告按钮 -->
            <el-button type="success" v-if="userRole===0" @click="showAddNoticeDialog">添加公告</el-button>
          </el-form-item>
          <el-form-item>
            <!-- 查询草稿箱按钮 -->
            <el-button type="warning" v-if="userRole===0" @click="searchDrafts">我的草稿箱</el-button>
          </el-form-item>
          <el-form-item>
            <!-- 批量删除按钮 -->
            <el-button 
              type="danger" 
              :disabled="selectedNotices.length === 0"
              @click="batchDelete"
              v-if="userRole===0"
            >
              批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="noticeList.records"
      style="width: 100%"
      :border="true"
      stripe
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选框列 -->
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <!-- 标题 -->
      <el-table-column prop="title" label="标题" min-width="150">
        <template #default="scope">
          <span class="ellipsis">{{ scope.row.title }}</span>
        </template>
      </el-table-column>

      <!-- 内容 -->
      <el-table-column prop="content" label="内容" min-width="200">
        <template #default="scope">
          <span class="ellipsis">{{ scope.row.content }}</span>
        </template>
      </el-table-column>

      <!-- 发布状态 -->
      <el-table-column prop="state" label="发布状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.state === 1 ? 'success' : 'info'">
            {{ scope.row.state === 1 ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 创建时间 -->
      <el-table-column prop="creatTime" label="创建时间" width="180"></el-table-column>

      <!-- 修改时间 -->
      <el-table-column prop="updateTime" label="修改时间" width="180"></el-table-column>

      <!-- 发布人 -->
      <el-table-column prop="publishUserName" label="发布人" width="120"></el-table-column>

      <!-- 修改人 -->
      <el-table-column prop="updateUserName" label="修改人" width="120"></el-table-column>

      <!-- 操作列 -->
      <el-table-column v-if="userRole===0" label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            class="operation-button"
            icon="el-icon-edit"
            size="small"
            @click="editNotice(scope.row)"
            circle
          ></el-button>
          <el-button 
            type="success" 
            class="operation-button" 
            icon="el-icon-upload2" 
            size="small" 
            @click="publishNotice(scope.row)" 
            v-if="scope.row.state === 0"
            circle
          ></el-button>
          <el-button 
            type="danger" 
            class="operation-button" 
            icon="el-icon-delete" 
            size="small" 
            @click="deleteNotice(scope.row)" 
            circle
            v-if="userRole===0"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: center;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="noticeList.total"
        :current-page="noticeList.current"
        :page-size="noticeList.size"
        :page-sizes="[3, 4, 5]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 添加公告对话框 -->
    <el-dialog title="添加公告" :visible.sync="addNoticeDialogVisible" width="50%" :close-on-click-modal="false">
      <el-form :model="newNotice" label-width="100px" :rules="rules" ref="newNoticeForm">
        <el-form-item label="标题" prop="title">
          <el-input style="width: 570px;" v-model="newNotice.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input style="width: 570px;" type="textarea" v-model="newNotice.content" placeholder="请输入内容" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="发布状态" prop="state">
          <el-select v-model="newNotice.state" placeholder="请选择状态" style="width: 570px;">
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="已发布" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addNoticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="showConfirmDialog">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑公告对话框 -->
    <el-dialog title="编辑公告" :visible.sync="editNoticeDialogVisible" width="50%" :close-on-click-modal="false">
      <el-form :model="editNoticeForm" label-width="100px" :rules="rules" ref="editNoticeForm">
        <el-form-item label="标题" prop="title">
          <el-input style="width: 570px;" v-model="editNoticeForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input style="width: 570px;" type="textarea" v-model="editNoticeForm.content" placeholder="请输入内容" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="发布状态" prop="state">
          <el-select v-model="editNoticeForm.state" placeholder="请选择状态" style="width: 570px;">
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="已发布" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editNoticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="showEditConfirmDialog">确定</el-button>
      </span>
    </el-dialog>

    <!-- 确认提交公告对话框 -->
    <el-dialog
      title="确认添加公告"
      :visible.sync="confirmDialogVisible"
      width="40%"
      center
      :close-on-click-modal="false"
    >
      <div class="confirm-content">
        <p><strong>标题：</strong>{{ newNotice.title }}</p>
        <p><strong>内容：</strong>{{ newNotice.content }}</p>
        <p><strong>状态：</strong>{{ newNotice.state === 1 ? '已发布' : '草稿' }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addNotice">确定</el-button>
      </span>
    </el-dialog>

    <!-- 确认编辑公告对话框 -->
    <el-dialog
      title="确认编辑公告"
      :visible.sync="editConfirmDialogVisible"
      width="40%"
      center
      :close-on-click-modal="false"
    >
      <div class="confirm-content">
        <p><strong>标题：</strong>{{ editNoticeForm.title }}</p>
        <p><strong>内容：</strong>{{ editNoticeForm.content }}</p>
        <p><strong>状态：</strong>{{ editNoticeForm.state === 1 ? '已发布' : '草稿' }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editConfirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateNotice">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userRole: null,
      // 表格数据
      noticeList: {},
      // 选中的公告
      selectedNotices: [],
      // 搜索表单
      searchForm: {
        title: '',
        state: '',
        startTime: '',
        endTime: ''
      },
      // 管理员列表
      managerOptions: {}, // 用于下拉列表
      // 新公告表单
      newNotice: {
        title: '',
        content: '',
        state: 0 // 默认草稿状态
      },
      // 编辑公告表单
      editNoticeForm: {
        id: '',
        title: '',
        content: '',
        state: 0
      },
      // 控制添加公告对话框的显示
      addNoticeDialogVisible: false,
      // 控制编辑公告对话框的显示
      editNoticeDialogVisible: false,
      // 控制确认对话框的显示
      confirmDialogVisible: false,
      // 控制编辑确认对话框的显示
      editConfirmDialogVisible: false,
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择发布状态', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    // 从token中获取用户角色
    getUserRoleFromToken() {
      try {
        const loginUser = JSON.parse(localStorage.getItem("loginUser"));
        console.log('loginUser:', loginUser);
        if (loginUser && loginUser.token) {
          const base64Url = loginUser.token.split('.')[1];
          const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
          const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
          }).join(''));

          const payload = JSON.parse(jsonPayload);
          console.log('Token payload:', payload);
          // 修改role的解析逻辑
          if (payload.role !== undefined && payload.role !== null) {
            this.userRole = Number(payload.role);
          } else {
            this.userRole = null;
          }
          console.log('Parsed userRole:', this.userRole);
        }
      } catch (error) {
        console.error('解析token失败:', error);
        this.userRole = null;
      }
    },
    // 加载公告列表
    loadNotices(pageNum = 1, pageSize = 3) {
      this.$http.get("/zsd-merchant/notice/list", {
        params: {
          pageNum: pageNum,
          pageSize: pageSize,
          title: this.searchForm.title,
          state: this.searchForm.state,
          startTime: this.searchForm.startTime,
          endTime: this.searchForm.endTime
        }
      })
      .then((resp) => {
        if (resp.data.code === 200) {
          // 格式化时间
          resp.data.data.records = resp.data.data.records.map(notice => ({
            ...notice,
            creatTime: notice.creatTime ? notice.creatTime.replace('T', ' ') : '',
            updateTime: notice.updateTime ? notice.updateTime.replace('T', ' ') : ''
          }));
          this.noticeList = resp.data.data;
        }
      });
    },

    // 搜索公告
    searchNotices() {
      this.loadNotices(1, this.noticeList.size); // 重置到第一页并应用搜索条件
    },

    // 显示添加公告对话框
    showAddNoticeDialog() {
      this.addNoticeDialogVisible = true;
      // 清空新公告表单
      this.newNotice = {
        title: '',
        content: '',
        state: 0
      };
      // 重置表单验证
      this.$refs.newNoticeForm && this.$refs.newNoticeForm.resetFields();
    },

    // 显示确认对话框
    showConfirmDialog() {
      this.$refs.newNoticeForm.validate((valid) => {
        if (valid) {
          this.confirmDialogVisible = true;
        } else {
          this.$message.error('请检查输入信息');
          return false;
        }
      });
    },

    // 提交新公告
    addNotice() {
      this.$http.post("/zsd-merchant/notice/publish", {
        title: this.newNotice.title,
        content: this.newNotice.content,
        state: this.newNotice.state
      })
        .then((resp) => {
          if (resp.data.code === 200) {
            this.$message({
              message: this.newNotice.state === 1 ? '公告发布成功' : '保存草稿成功',
              type: 'success'
            });
            this.addNoticeDialogVisible = false;
            this.confirmDialogVisible = false;
            // 重新加载公告列表
            this.loadNotices(1, this.noticeList.size);
          } else {
            this.$message.error(resp.data.msg || '操作失败');
          }
        })
        .catch((error) => {
          console.error('操作失败:', error);
          this.$message.error('操作失败，请稍后再试');
        });
    },

    // 显示编辑公告对话框
    editNotice(row) {
      // 将当前公告信息填充到编辑表单中
      this.editNoticeForm = {
        id: row.id,
        title: row.title,
        content: row.content,
        state: row.state
      };
      this.editNoticeDialogVisible = true;
    },

    // 显示编辑确认对话框
    showEditConfirmDialog() {
      this.$refs.editNoticeForm.validate((valid) => {
        if (valid) {
          this.editConfirmDialogVisible = true;
        } else {
          this.$message.error('请检查输入信息');
          return false;
        }
      });
    },

    // 提交编辑后的公告
    updateNotice() {
      this.$http.put('/zsd-merchant/notice/update', {
        id: this.editNoticeForm.id,
        title: this.editNoticeForm.title,
        content: this.editNoticeForm.content,
        state: this.editNoticeForm.state
      })
        .then((resp) => {
          if (resp.data.code === 200) {
            this.$message({
              message: this.editNoticeForm.state === 1 ? '公告发布成功' : '保存草稿成功',
              type: 'success'
            });
            this.editNoticeDialogVisible = false;
            this.editConfirmDialogVisible = false;
            // 重新加载公告列表
            this.loadNotices(1, this.noticeList.size);
          } else {
            this.$message.error(resp.data.msg || '操作失败');
          }
        })
        .catch((error) => {
          console.error('操作失败:', error);
          this.$message.error('操作失败，请稍后再试');
        });
    },

    // 删除公告
    deleteNotice(row) {
      this.$confirm('确认删除该公告吗？删除后将无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('/zsd-merchant/notice/delete', {
          params: {
            ids: row.id
          }
        })
          .then((resp) => {
            if (resp.data.code === 200) {
              this.$message({
                message: '公告删除成功',
                type: 'success'
              });
              // 重新加载草稿箱
              this.loadNotices();
            } else {
              this.$message.error(resp.data.msg || '公告删除失败');
            }
          })
          .catch((error) => {
            console.error('公告删除失败:', error);
            this.$message.error('公告删除失败，请稍后再试');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 分页大小改变时触发
    handleSizeChange(pageSize) {
      this.loadNotices(1, pageSize);
    },

    // 当前页码改变时触发
    handleCurrentChange(pageNum) {
      this.loadNotices(pageNum, this.noticeList.size);
    },

    // 加载管理员列表
    loadManagers() {
      this.$http.get('/managerInfo/realName')
        .then((resp) => {
          this.managerOptions = resp.data.data
          console.log(this.managerOptions);
        })
    },

    // 查询草稿箱
    searchDrafts() {
      this.$http.get("/zsd-merchant/notice/draft")
        .then((resp) => {
          if (resp.data.code === 200) {
            // 格式化时间
            const formattedRecords = resp.data.data.map(notice => ({
              ...notice,
              creatTime: notice.creatTime ? notice.creatTime.replace('T', ' ') : '',
              updateTime: notice.updateTime ? notice.updateTime.replace('T', ' ') : ''
            }));
            this.noticeList = {
              records: formattedRecords,
              total: resp.data.data.length,
              current: 1,
              size: 3
            };
          } else {
            this.$message.error(resp.data.msg || '获取草稿箱失败');
          }
        })
        .catch((error) => {
          console.error('获取草稿箱失败:', error);
          this.$message.error('获取草稿箱失败，请稍后再试');
        });
    },

    // 发布公告
    publishNotice(row) {
      this.$confirm('确认发布该公告吗？发布后将无法修改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.put('/zsd-merchant/notice/update', {
          id: row.id,
          title: row.title,
          content: row.content,
          state: 1 // 设置为发布状态
        })
          .then((resp) => {
            if (resp.data.code === 200) {
              this.$message({
                message: '公告发布成功',
                type: 'success'
              });
              // 重新加载草稿箱
              this.loadNotices();
            } else {
              this.$message.error(resp.data.msg || '公告发布失败');
            }
          })
          .catch((error) => {
            console.error('公告发布失败:', error);
            this.$message.error('公告发布失败，请稍后再试');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消发布'
        });
      });
    },

    // 处理多选框变化
    handleSelectionChange(selection) {
      this.selectedNotices = selection;
    },

    // 批量删除
    batchDelete() {
      if (this.selectedNotices.length === 0) {
        this.$message.warning('请选择要删除的公告');
        return;
      }

      this.$confirm(`确认删除选中的 ${this.selectedNotices.length} 条公告吗？删除后将无法恢复`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedNotices.map(item => item.id);
        this.$http.delete('/zsd-merchant/notice/delete', {
          params: {
            ids: ids.join(',')
          }
        })
          .then((resp) => {
            if (resp.data.code === 200) {
              this.$message({
                message: '批量删除成功',
                type: 'success'
              });
              // 重新加载草稿箱
              this.loadNotices();
              // 清空选中
              this.selectedNotices = [];
            } else {
              this.$message.error(resp.data.msg || '批量删除失败');
            }
          })
          .catch((error) => {
            console.error('批量删除失败:', error);
            this.$message.error('批量删除失败，请稍后再试');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  created() {
    // 初始化加载公告列表
    this.loadNotices();
    // 初始化加载管理员列表
    this.loadManagers();
    // 从token中获取用户角色
    this.getUserRoleFromToken();
  }
};
</script>

<style scoped>

/* 搜索栏样式 */
.search-bar {
  border-bottom: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  background-color: #fff;
  margin-bottom: 20px;
}

/* 表格样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  height: 48px;
  line-height: 48px;
}

.el-table__row {
  height: 48px;
  line-height: 48px;
}

.el-table .cell {
  padding: 0 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ellipsis {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 10px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 20px;
  color: #606266;
}

.confirm-content p {
  margin: 10px 0;
  font-size: 16px;
}

.confirm-content strong {
  color: #409EFF;
}

.el-dialog__footer {
  padding: 10px 20px;
  border-top: 1px solid #ebeef5;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button--text {
  color: #409EFF;
}

.el-button--text:hover {
  color: #66b1ff;
}

/* 表单样式 */
.demo-form-inline .el-form-item {
  margin-bottom: 0;
}

.demo-form-inline .el-input, .demo-form-inline .el-date-picker {
  width: 200px;
}


</style>